<template>
  <div class="user-profile max-w-7xl mx-auto px-4 py-8">
    <!-- 个人信息卡片 -->
    <div class="bg-white rounded-lg shadow p-6 mb-8">
      <div class="flex items-start justify-between">
        <div class="flex items-center gap-4">
          <div class="relative group">
            <img
              :src="userStore.user?.avatar || '/default-avatar.png'"
              class="w-24 h-24 rounded-full object-cover transition-opacity group-hover:opacity-80"
              alt="用户头像"
            />
            <div
              @click="showAvatarModal = true"
              class="absolute inset-0 flex items-center justify-center rounded-full bg-black bg-opacity-0 group-hover:bg-opacity-40 transition-all cursor-pointer"
            >
              <div class="opacity-0 group-hover:opacity-100 text-white flex flex-col items-center">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"
                  />
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"
                  />
                </svg>
                <span class="text-sm mt-1">更换头像</span>
              </div>
            </div>
          </div>
          <div>
            <h2 class="text-2xl font-bold">{{ userStore.user?.nickName }}</h2>
            <p class="text-gray-500">@{{ userStore.user?.userName }}</p>
            <p class="mt-2">{{ userStore.user?.signature || '这个人很懒，什么都没写~' }}</p>
          </div>
        </div>
        <button @click="showEditModal = true" class="bg-primary text-white px-4 py-2 rounded-md">
          编辑资料
        </button>
      </div>

      <div class="mt-6 grid grid-cols-3 gap-4">
        <div class="text-center">
          <p class="text-2xl font-bold">{{ userArticles.length }}</p>
          <p class="text-gray-500">文章</p>
        </div>
        <div class="text-center">
          <p class="text-2xl font-bold">{{ totalLikes }}</p>
          <p class="text-gray-500">获赞</p>
        </div>
        <div class="text-center">
          <p class="text-2xl font-bold">{{ totalViews }}</p>
          <p class="text-gray-500">阅读</p>
        </div>
      </div>
    </div>

    <!-- 我的文章列表 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h3 class="text-xl font-bold mb-4">我的文章</h3>
      <div v-if="userArticles.length" class="space-y-4">
        <div
          v-for="article in userArticles"
          :key="article.id"
          class="flex items-center justify-between p-4 hover:bg-gray-50 rounded-lg group"
        >
          <div class="flex-1 cursor-pointer" @click="goToArticleDetail(article.id)">
            <h4 class="font-medium group-hover:text-blue-600 transition-colors">
              {{ article.articleTitle }}
            </h4>
            <p class="text-sm text-gray-500">
              {{ new Date(article.createTime).toLocaleDateString() }}
            </p>
          </div>
          <div class="flex gap-2">
            <button
              @click.stop="handleEditArticle(article)"
              class="text-blue-500 hover:text-blue-700"
            >
              编辑
            </button>
            <button
              @click.stop="handleDeleteArticle(article.id)"
              class="text-red-500 hover:text-red-700"
            >
              删除
            </button>
          </div>
        </div>
      </div>
      <div v-else class="text-center py-8">
        <p class="text-gray-500 mb-4">还没有发布过文章哦~</p>
        <router-link
          to="/write"
          class="inline-flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M12 4v16m8-8H4"
            />
          </svg>
          <span>去写文章</span>
        </router-link>
      </div>
    </div>

    <!-- 编辑资料弹窗 - 使用 Modal 组件替换 Dialog -->
    <Modal :show="showEditModal" title="编辑个人资料" @close="showEditModal = false">
      <form @submit.prevent="handleUpdateProfile" class="space-y-4">
        <div>
          <label class="block text-sm font-medium mb-1">昵称</label>
          <input
            v-model="editForm.nickName"
            type="text"
            class="w-full rounded-md border-gray-300"
          />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">邮箱</label>
          <input v-model="editForm.email" type="email" class="w-full rounded-md border-gray-300" />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">手机号</label>
          <input
            v-model="editForm.phonenumber"
            type="tel"
            class="w-full rounded-md border-gray-300"
          />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">性别</label>
          <select v-model="editForm.sex" class="w-full rounded-md border-gray-300">
            <option value="0">男</option>
            <option value="1">女</option>
            <option value="2">未知</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">个性签名</label>
          <textarea
            v-model="editForm.signature"
            class="w-full rounded-md border-gray-300"
            rows="3"
          ></textarea>
        </div>
        <div class="flex justify-end gap-2">
          <button type="button" @click="showEditModal = false" class="px-4 py-2 border rounded-md">
            取消
          </button>
          <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md">保存</button>
        </div>
      </form>
    </Modal>

    <!-- 添加头像上传弹窗 -->
    <AvatarUploadModal
      :show="showAvatarModal"
      :current-avatar="userStore.user?.avatar"
      @close="showAvatarModal = false"
      @update="handleAvatarUpdate"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '@/store/modules/auth'
import { articleApi } from '@/api/article'
import type { ArticleVO } from '@/types'
import Modal from '@/components/common/Modal.vue'
import AvatarUploadModal from '@/components/user/AvatarUploadModal.vue'
import { useRouter } from 'vue-router'

const userStore = useAuthStore()
const router = useRouter()

const editForm = ref({
  nickName: '',
  email: '',
  phonenumber: '',
  sex: '0' as '0' | '1' | '2',
  signature: '',
})

const showEditModal = ref(false)
const showAvatarModal = ref(false)
const userArticles = ref<ArticleVO[]>([])

const totalLikes = computed(() => {
  return userArticles.value.reduce((sum, article) => sum + (article.liked || 0), 0)
})

const totalViews = computed(() => {
  return userArticles.value.length * 100
})

const fetchUserArticles = async () => {
  try {
    if (!userStore.user?.id) return

    const response = await articleApi.getUserArticles(userStore.user.id)
    if (response.code === 200) {
      userArticles.value = response.data || []
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
  }
}

const handleUpdateProfile = async () => {
  try {
    if (!userStore.user?.id) return

    const success = await userStore.updateProfile({
      id: userStore.user.id,
      nickName: editForm.value.nickName,
      email: editForm.value.email,
      phonenumber: editForm.value.phonenumber,
      sex: editForm.value.sex,
      signature: editForm.value.signature,
      avatar: userStore.user.avatar,
    })

    if (success) {
      showEditModal.value = false
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
  }
}

const handleEditArticle = (article: ArticleVO) => {
  router.push({
    path: '/write',
    query: { id: article.id.toString() },
  })
}

const handleDeleteArticle = async (id: number) => {
  try {
    const response = await articleApi.delete(id)
    if (response.code === 200) {
      await fetchUserArticles()
    }
  } catch (error) {
    console.error('删除文章失败:', error)
  }
}

const handleAvatarUpdate = async (avatar: string) => {
  try {
    const success = await userStore.updateAvatar(avatar)
    if (success) {
      showAvatarModal.value = false
    }
  } catch (error) {
    console.error('更新头像失败:', error)
  }
}

const goToArticleDetail = (articleId: number) => {
  router.push(`/article/${articleId}`)
}

onMounted(async () => {
  try {
    if (!userStore.user) {
      await userStore.checkAuth()
    }

    await fetchUserArticles()

    if (userStore.user) {
      editForm.value = {
        nickName: userStore.user.nickName || '',
        email: userStore.user.email || '',
        phonenumber: userStore.user.phonenumber || '',
        sex: userStore.user.sex || '0',
        signature: userStore.user.signature || '',
      }
    }
  } catch (error) {
    console.error('初始化失败:', error)
  }
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
}

/* 添加过渡动画 */
.transition-opacity {
  transition: opacity 0.3s ease;
}

.transition-all {
  transition: all 0.3s ease;
}
</style>
